﻿using System;
using UnityEngine;

[LuaExport]
class SendBaseMessage
{
    private ByteArray inner;
    private int opcode;
    public SendBaseMessage()
    {
        inner = new ByteArray();
        inner.WriteInt(0);
        inner.WriteInt(0);
    }
    public SendBaseMessage(int opcode)
    {
        this.opcode = opcode;
    }
    public void WriteByte(int value)
    {
        inner.WriteByte((byte)value);
    }
    public void WriteShort(int value)
    {
        inner.WriteShort((short)value);
    }
    public void WriteInt(int value)
    {
        inner.WriteInt(value);
    }
    public void WriteFloat(float value)
    {
        inner.WriteFloat(value);
    }
    public void WriteDouble(double value)
    {
        inner.WriteDouble(value);
    }
    public void WriteLong(long value)
    {
        inner.WriteLong(value);
    }
    public void WriteString(string value)
    {
        inner.WriteString(value);
    }
    public void SendToServer()
    {
        Type type = this.GetType();
        var classAttribute = (Opcode)Attribute.GetCustomAttribute(type, typeof(Opcode));
        if (classAttribute != null)
        {
            int opcode = classAttribute.Id;
            int length = inner.Length;
            int pos = inner.Position;
            inner.Position = 0;
            inner.WriteShort(127);
            inner.WriteShort((short)length);
            inner.WriteInt(opcode);
            inner.Position = pos;
            SocketHelper.GetInstance().SendMsg(inner.ToArray());
        }
        else {
            int length = inner.Length;
            int pos = inner.Position;
            inner.Position = 0;
            inner.WriteShort(127);
            inner.WriteShort((short)length);
            inner.WriteInt(opcode);
            inner.Position = pos;
            SocketHelper.GetInstance().SendMsg(inner.ToArray());
        }
    }
}

